<?php
/**
 * OA模块
 */

declare (strict_types=1);

namespace app\oa\controller;

use app\base\BaseController;
use app\load\loadModel\HaiModel;
use app\load\loadModel\OaModel;
use app\load\loadServices\OaServices;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class Approve extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = [];
            if (isset($param['status'])) {
                if ($param['status'] == 1) {
                    $where[] = ['check_status', '<', 2];
                }
                if ($param['status'] == 2) {
                    $where[] = ['check_status', '=', 2];
                }
                if ($param['status'] == 3) {
                    $where[] = ['check_status', '>', 2];
                }
            }
            $where[] = ['admin_id', '=', $this->uid];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];

            $list = OaModel::Approve()->list(
                $where,
                $rows ,
                $param,
                'f.*,a.name,d.title as department_name,t.title as flow_type');

            return table_assign(0, '', $list);
        } else {
            $uid = $this->uid;
            $department = $this->did;
            if ($uid == 1) {
                $list = Db::name('FlowType')->where(['status' => 1])->select()->toArray();
            } else {
                $map1 = [];
                $map2 = [];
                $map1[] = ['status', '=', 1];
                $map1[] = ['department_ids', '=', ''];

                $map2[] = ['status', '=', 1];
                $map2[] = ['', 'exp', Db::raw("FIND_IN_SET('{$department}',department_ids)")];

                $list = Db::name('FlowType')->whereOr([$map1, $map2])->select()->toArray();
            }
            View::assign('list', $list);
            View::assign('type', get_config('approve.type'));
            return view();
        }
    }

    public function list()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $status = isset($param['status']) ? $param['status'] : 0;
            $user_id = $this->uid;
            //查询条件
            $map1 = [];
            $map2 = [];
            $map1[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',f.check_admin_ids)")];
            $map2[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',f.flow_admin_ids)")];

            if (!empty($param['type'])) {
                $map1[] = ['f.type', '=', $param['type']];
                $map2[] = ['f.type', '=', $param['type']];
            }
            if (!empty($param['uid'])) {
                $map1[] = ['f.admin_id', '=', $param['uid']];
                $map2[] = ['f.admin_id', '=', $param['uid']];
            }
            //按时间检索
            $start_time = isset($param['start_time']) ? strtotime($param['start_time']) : 0;
            $end_time = isset($param['end_time']) ? strtotime($param['end_time']) : 0;
            if ($start_time > 0 && $end_time > 0) {
                $map1[] = ['f.create_time', 'between', [$start_time, $end_time]];
                $map2[] = ['f.create_time', 'between', [$start_time, $end_time]];
            }

            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];

            if ($status == 0) {
                $list = Db::name('Approve')
                    ->field('f.*,a.name,d.title as department_name,t.title as flow_type')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.admin_id', 'left')
                    ->join('Department d', 'd.id = f.department_id', 'left')
                    ->join('FlowType t', 't.id = f.type', 'left')
                    ->whereOr([$map1, $map2])
                    ->order('f.id desc')
                    ->group('f.id')
                    ->paginate(['list_rows' => $rows, 'query' => $param])
                    ->each(function ($item, $key) {
                        $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                        $item['check_user'] = '-';
                        if ($item['check_status'] < 2 && !empty($item['check_admin_ids'])) {
                            $check_user = Db::name('Admin')->where('id', 'in', $item['check_admin_ids'])->column('name');
                            $item['check_user'] = implode(',', $check_user);
                        }
                        return $item;
                    });
            }

            if ($status == 1) {
                $list = Db::name('Approve')
                    ->field('f.*,a.name,d.title as department_name,t.title as flow_type')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.admin_id', 'left')
                    ->join('Department d', 'd.id = f.department_id', 'left')
                    ->join('FlowType t', 't.id = f.type', 'left')
                    ->where($map1)
                    ->order('f.id desc')
                    ->group('f.id')
                    ->paginate(['list_rows' => $rows, 'query' => $param])
                    ->each(function ($item, $key) {
                        $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                        $item['check_user'] = '-';
                        if ($item['check_status'] < 2 && !empty($item['check_admin_ids'])) {
                            $check_user = Db::name('Admin')->where('id', 'in', $item['check_admin_ids'])->column('name');
                            $item['check_user'] = implode(',', $check_user);
                        }
                        return $item;
                    });
            }
            if ($status == 2) {
                $list = Db::name('Approve')
                    ->field('f.*,a.name,d.title as department_name,t.title as flow_type')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.admin_id', 'left')
                    ->join('Department d', 'd.id = f.department_id', 'left')
                    ->join('FlowType t', 't.id = f.type', 'left')
                    ->where($map2)
                    ->order('f.id desc')
                    ->group('f.id')
                    ->paginate(['list_rows' => $rows, 'query' => $param])
                    ->each(function ($item, $key) {
                        $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                        $item['check_user'] = '-';
                        if ($item['check_status'] < 2 && !empty($item['check_admin_ids'])) {
                            $check_user = Db::name('Admin')->where('id', 'in', $item['check_admin_ids'])->column('name');
                            $item['check_user'] = implode(',', $check_user);
                        }
                        return $item;
                    });
            }
            return table_assign(0, '', $list);
        } else {
            $type = Db::name('FlowType')->whereOr('status', 1)->select()->toArray();
            View::assign('type', $type);
            return view();
        }
    }

    public function copy()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $user_id = $this->uid;
            //查询条件
            $map = [];
            $map[] = ['f.check_status', '=', 2];
            $map[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',f.copy_uids)")];
            if (!empty($param['type'])) {
                $map[] = ['f.type', '=', $param['type']];
            }
            if (!empty($param['uid'])) {
                $map[] = ['f.admin_id', '=', $param['uid']];
            }
            //按时间检索
            $start_time = isset($param['start_time']) ? strtotime($param['start_time']) : 0;
            $end_time = isset($param['end_time']) ? strtotime($param['end_time']) : 0;
            if ($start_time > 0 && $end_time > 0) {
                $map[] = ['f.create_time', 'between', [$start_time, $end_time]];
            }

            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name('Approve')
                ->field('f.*,a.name,d.title as department_name,t.title as flow_type')
                ->alias('f')
                ->join('Admin a', 'a.id = f.admin_id', 'left')
                ->join('Department d', 'd.id = f.department_id', 'left')
                ->join('FlowType t', 't.id = f.type', 'left')
                ->where($map)
                ->order('f.id desc')
                ->group('f.id')
                ->paginate(['list_rows' => $rows, 'query' => $param])
                ->each(function ($item, $key) {
                    $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                    $item['check_user'] = '-';
                    if ($item['check_status'] < 2 && !empty($item['check_admin_ids'])) {
                        $check_user = Db::name('Admin')->where('id', 'in', $item['check_admin_ids'])->column('name');
                        $item['check_user'] = implode(',', $check_user);
                    }
                    return $item;
                });
            return table_assign(0, '', $list);
        } else {
            $type = Db::name('FlowType')->whereOr('status', 1)->select()->toArray();
            View::assign('type', $type);
            return view();
        }
    }


    /**
     * 添加新增/编辑
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function add()
    {
        $param = get_params();

        if (request()->isAjax()) {

            if (isset($param['detail_time'])) {
                $param['detail_time'] = strtotime($param['detail_time']);
            }

            if (isset($param['start_time'])) {
                $param['start_time'] = strtotime($param['start_time']);
            }

            if (isset($param['end_time'])) {
                $param['end_time'] = strtotime($param['end_time']);
                if ($param['end_time'] < $param['start_time']) {
                    return to_assign(1, "时间选择有误");
                }
            }

            if (isset($param['start_time_a'])) {
                $param['start_time'] = strtotime($param['start_time_a'] . '' . $param['start_time_b']);
            }

            if (isset($param['end_time_a'])) {
                $param['end_time'] = strtotime($param['end_time_a'] . '' . $param['end_time_b']);
                if ($param['end_time'] <= $param['start_time']) {
                    return to_assign(1, "结束时间需要大于开始时间");
                }
            }

            if (empty($param['flow_id'])) {
                return to_assign(1, "请选择审批类型");
            }
            OaServices::Oa()->save($param, $this->uid, $this->did);
            return to_assign();

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $type = isset($param['type']) ? $param['type'] : 0;

            $product_list = [];
            if ($type == 15) {
                $product_list = HaiModel::Product()->all_list([['status', '<>', '-1']], 'product_sn,product_name');
            }

            if ($id > 0) {
                $detail = Db::name('Approve')->where('id', $id)->find();
                if ($detail['type'] == 15) {
                    $product_list = HaiModel::Product()->all_list([['status', '<>', '-1']], 'product_sn,product_name');
                }
                $detail['start_time_a'] = date('Y-m-d', $detail['start_time']);
                $detail['start_time_b'] = date('H:i', $detail['start_time']);
                $detail['end_time_a'] = date('Y-m-d', $detail['end_time']);
                $detail['end_time_b'] = date('H:i', $detail['end_time']);
                $detail['detail_time'] = date('Y-m-d', $detail['detail_time']);

                $detail['days'] = floor($detail['duration'] * 10 / 80);
                $detail['hours'] = (($detail['duration'] * 10) % 80) / 10;
                $type = $detail['type'];
                if ($detail['file_ids'] != '') {
                    $fileArray = Db::name('File')->where('id', 'in', $detail['file_ids'])->select();
                    $detail['fileArray'] = $fileArray;
                }
                $detail['product_list'] = $product_list;
                $detail['product_info'] = OaModel::PurchaseProduct()->list(['approve_id' => $detail['id']]);
                View::assign('detail', $detail);
            }

            $department = $this->did;
            //获取审批流程
            $flows = get_cate_department_flows($type, $department);
            $moban = Db::name('FlowType')->where('id', $type)->value('name');
            $module = strtolower(app('http')->getName());
            $class = strtolower(app('request')->controller());
            $action = strtolower(app('request')->action());
            $template = $module . '/view/' . $class . '/add_' . $moban . '.html';

            View::assign([
                'flows' => $flows,
                'id' => $id,
                'type' => $type,
                'admin_info' => get_admin($this->uid),
                'product_list' => $product_list
            ]);
            if (isTemplate($template)) {
                return view('add_' . $moban);
            } else {
                return view('../../base/view/common/errortemplate', ['file' => $template]);
            }
        }
    }

    /**
     * 查看
     * @return \think\response\View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function view(): \think\response\View
    {
        $param = get_params();
        $detail = Db::name('Approve')->where('id', $param['id'])->find();
        $check_record = [];

        $detail['start_time'] = $detail['start_time'] > 0 ? date('Y-m-d H:i', $detail['start_time']) : '';
        $detail['end_time'] = $detail['end_time'] > 0 ? date('Y-m-d H:i', $detail['end_time']) : '';
        $detail['detail_time'] = $detail['detail_time'] > 0 ? date('Y-m-d', $detail['detail_time']) : '';

        if ($detail['type']) {
            $detail['list'] = Db::name('PurchaseProduct')->where('approve_id', $detail['id'])->select();
        }

        $detail['days'] = floor($detail['duration'] * 10 / 80);
        $detail['hours'] = (($detail['duration'] * 10) % 80) / 10;

        $detail['create_user'] = Db::name('Admin')->where('id', $detail['admin_id'])->value('name');
        $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 1, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
        $detail['check_user'] = '-';
        $detail['copy_user'] = '-';
        $check_user_ids = [];

        if ($detail['check_status'] < 2) {
            if ($flows['flow_type'] == 1) {
                $detail['check_user'] = '部门负责人';
                $check_user_ids = explode(',', $detail['check_admin_ids']);
            } else if ($flows['flow_type'] == 2) {
                $detail['check_user'] = '上级部门负责人';
                $check_user_ids = explode(',', $detail['check_admin_ids']);
            } else {
                $check_user_ids = explode(',', $flows['flow_uids']);
                $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                $detail['check_user'] = implode(',', $check_user);
            }
        }

        if (!empty($detail['copy_uids'])) {
            $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
            $detail['copy_user'] = implode(',', $copy_user);
        }

        if (!empty($detail['file_ids'])) {
            $fileArray = Db::name('File')->where('id', 'in', $detail['file_ids'])->select();
            $detail['fileArray'] = $fileArray;
        }

        $is_check_admin = 0;
        $is_create_admin = 0;

        if ($detail['admin_id'] == $this->uid) {
            $is_create_admin = 1;
        }

        if (in_array($this->uid, $check_user_ids)) {
            $is_check_admin = 1;
            $step = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 1, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();

            if ($step['flow_type'] == 4) {
                $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 1, 'step_id' => $step['id'], 'check_user_id' => $this->uid])->count();

                if ($check_count > 0) {
                    $is_check_admin = 0;
                }
            }
        }

        $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
            ->alias('f')
            ->join('Admin a', 'a.id = f.check_user_id', 'left')
            ->where(['f.action_id' => $detail['id'], 'f.type' => 1])
            ->order('check_time desc')
            ->select()
            ->toArray();

        foreach ($check_record as &$record) {
            $record['check_time_str'] = date('Y-m-d H:i', $record['check_time']);
            $record['status_str'] = '提交';

            if ($record['status'] == 1) {
                $record['status_str'] = '审核通过';
            } else if ($record['status'] == 2) {
                $record['status_str'] = '审核拒绝';
            } else if ($record['status'] == 3) {
                $record['status_str'] = '撤销';
            }

            if (!empty($record['image'])) {
                $record['image'] = env('url') . $record['image'];
            }
        }
//        print_r($check_record);die;
        $moban = Db::name('FlowType')->where('id', $detail['type'])->value('name');
        $module = strtolower(app('http')->getName());
        $class = strtolower(app('request')->controller());
        $action = strtolower(app('request')->action());
        $template = $module . '/view/' . $class . '/view_' . $moban . '.html';

        View::assign([
            'is_create_admin' => $is_create_admin,
            'is_check_admin' => $is_check_admin,
            'check_record' => $check_record,
            'detail' => $detail,
            'flows' => $flows,
        ]);

        if (isTemplate($template)) {
            return view('view_' . $moban);
        } else {
            return view('../../base/view/common/errortemplate', ['file' => $template]);
        }
    }


    /**
     *  删除添加商品
     * 【id】 添加商品的id
     */
    public function del_product()
    {
        $input = input('post.');
        try {
            $result = OaServices::Oa()->delProduct(['id' => $input['id']]);
            if (!$result) {
                throw new Exception('操作失败');
            }
            return to_assign();
        } catch (Exception $e) {
            return to_assign(1, $e->getMessage());
        }
    }


    /**
     *  签名页面
     */
    public function check_sign()
    {
        $input = input();
        View::assign('data', [
            'id' => $input['id'],
            'content' => $input['content'],
            'check_node' => $input['check_node'],
            'check_admin_ids' => $input['check_admin_ids'] != null ? $input['check_admin_ids'] : "0",
            'check' => $input['check'],
            'type' => $input['type'],
        ]);
        return view();
    }
}
